﻿using Consul;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Ocelot.ConsulExtensions.Model;
using Ocelot.DependencyInjection;
using Ocelot.Provider.Consul;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Ocelot.ConsulExtensions
{
    /// <summary>
    /// 网关消费者拓展
    /// </summary>
    public static class ConsulConsumerExtensions
    {

        public static async Task<List<string>> GetServices(string consulAddress,string serviceName)
        {
            ConsulClient consulClient = new ConsulClient(configuration =>
            {
                //服务注册地址：集群中任意一个地址
                configuration.Address = new Uri(consulAddress);
            });
            //consulClient.
            QueryResult<CatalogService[]> result = await consulClient.Catalog.Service(serviceName);
            List<string> list = new List<string>();
            if (result?.Response != null && result?.Response.Length > 0)
            {
                foreach (CatalogService item in result.Response)
                {
                    list.Add($"{item.ServiceAddress}:{item.ServicePort}");
                }
            }
            return list;
        }

        public static IServiceCollection AddConsulDiscovery(this IServiceCollection services, string consulAddress, string datacenter = "dc1")
        {
            ConsulClient client = new ConsulClient(conf =>
            {
                conf.Address = new Uri(consulAddress);
                conf.Datacenter = datacenter;
            });
            return services.AddSingleton(client);
        }

    }
}